package com.gds.wiki.cloud.framework.common.dto;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.gds.wiki.cloud.framework.common.constants.AppConstant;
import com.gds.wiki.cloud.framework.common.exception.BizExceptionEnum;
import com.gds.wiki.cloud.framework.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Member;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 服务器响应结果对象
 *
 * @author WIKI
 *
 * @param <T>
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseDto<T> {
    /**
     * 服务器响应编号
     */
    private String code;
    /**
     * 服务器响应消息
     */
    private String mesg;
    /**
     * 服务器响应结果对象
     */
    private T data;

    public  ResponseDto(BizExceptionEnum bizExceptionEnum){
          this.code=bizExceptionEnum.getCode();
          this.mesg=bizExceptionEnum.getMessage();
    }

    public  ResponseDto(BusinessException businessException){
        this.code=businessException.getCode();
        this.mesg=businessException.getMessage();
    }

    public  ResponseDto(BizExceptionEnum bizExceptionEnum,T t){
        this.code=bizExceptionEnum.getCode();
        this.mesg=bizExceptionEnum.getMessage();
    }

    public  ResponseDto(String code,String mesg){
        this.code=code;
        this.mesg=mesg;
    }

    public void ChangeBizException(BizExceptionEnum bizExceptionEnum){
        this.code=bizExceptionEnum.getCode();
        this.mesg=bizExceptionEnum.getMessage();

    }

    public T responseData(Class<T> beanClass){
        if(code.equals(AppConstant.Code.ERROR)){
             throw new BusinessException(this.code,this.mesg);
        }else {
            if(data instanceof LinkedHashMap && beanClass!=null){
                return BeanUtil.mapToBean((Map<?, ?>) data,beanClass,false);
            }else {
                return data;
            }
        }
    }
}
